package cn.com.self.apis.portal.service.impl;

import cn.com.self.apis.files.entity.Files;
import cn.com.self.apis.files.service.IFilesService;
import cn.com.self.apis.member.entity.UTalentRecommendationVO;
import cn.com.self.apis.portal.entity.ClassificationRelationEntity;
import cn.com.self.apis.portal.entity.FileRelationEntity;
import cn.com.self.apis.portal.entity.RequirementsEntity;
import cn.com.self.apis.portal.entity.dto.RequirementsDTO;
import cn.com.self.apis.portal.entity.dto.RequirementsDTO2;
import cn.com.self.apis.portal.mapper.RequirementsMapper;
import cn.com.self.apis.portal.service.intf.IClassificationRelationService;
import cn.com.self.apis.portal.service.intf.IFileRelationService;
import cn.com.self.apis.portal.service.intf.IRequirementsService;
import cn.com.self.apis.portal.util.*;
import cn.com.self.apis.util.CopyUtils;
import cn.com.selfsoft.smartcity.commons.http.DataItem;
import cn.com.selfsoft.smartcity.commons.http.DataPage;
import cn.com.selfsoft.smartcity.commons.util.ParameterUtil;
import cn.com.selfsoft.smartcity.core.service.BaseServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.data.domain.Pageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;

import static cn.com.self.apis.portal.util.ConstantUtils.FILE_TYPE_XUQIU;

/**
 * @author CRL
 * @date 2021/1/9 14:28
 */
@Service
public class RequirementsServiceImpl extends BaseServiceImpl<RequirementsEntity, String> implements IRequirementsService {

    @Autowired
    IRequirementsService requirementsService;
    @Autowired
    IFileRelationService fileRelationService;
    @Autowired
    IFilesService filesService;
    @Autowired
    IClassificationRelationService classificationRelationService;
    @Autowired
    RequirementsMapper requirementsMapper;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public ResponseEntity createRequirements(RequirementsDTO requestBody) {
        RequirementsEntity requirementsEntity = new RequirementsEntity();
        requestBody.setCreateDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
        requestBody.setUpdateDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
        CopyUtils.copyProperties(requestBody, requirementsEntity);
        RequirementsEntity requirements = requirementsService.create(requirementsEntity);
        Long objId = requirements.getId();
        String classificationId = requirements.getClassificationId();
        List<Files> files = requirementsEntity.getFiles();
        if (files != null) {
            for (Files fileId : files) {
                FileRelationEntity relationEntity = new FileRelationEntity();
                relationEntity.setFileId(String.valueOf(fileId.getId()));
                relationEntity.setObjId(String.valueOf(objId));
                relationEntity.setType(FILE_TYPE_XUQIU);
                fileRelationService.create(relationEntity);
            }
        }
        ClassificationRelationEntity classificationRelationEntity = new ClassificationRelationEntity();
        classificationRelationEntity.setClassificationInfoId(classificationId);
        classificationRelationEntity.setObjId(String.valueOf(objId));
        classificationRelationService.create(classificationRelationEntity);
        return ResponseEntity.status(HttpStatus.OK).body(new cn.com.selfsoft.smartcity.commons.http.ResultModel<>(new DataItem(requirementsEntity)));
    }

    @Override
    public ResponseEntity deletesRequirements(String id) {
        requirementsService.delete(id);
        //删除附件关系表
        fileRelationService.deleteByObjId(id);
        return ResponseEntity.status(HttpStatus.OK).body(new cn.com.selfsoft.smartcity.commons.http.ResultModel<>(1));
    }

    @Override
    public ResponseEntity updateRequirements(String id, RequirementsDTO requestBody) {
        RequirementsEntity requirementsEntity = this.requirementsService.load(id);
        requirementsEntity.setUpdateDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
        cn.com.self.apis.util.CopyUtils.copyProperties(requestBody, requirementsEntity);
        requirementsEntity.setUpdateDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
        RequirementsEntity info = this.requirementsService.update(requirementsEntity);
        //更新附件信息
        List<Files> files = requestBody.getFiles();
        if (files != null) {
            fileRelationService.deleteByObjId(id);
            for (Files file : files) {
                FileRelationEntity relationEntity = new FileRelationEntity();
                relationEntity.setFileId(String.valueOf(file.getId()));
                relationEntity.setObjId(id);
                fileRelationService.create(relationEntity);
            }
        }
        return ResponseEntity.status(HttpStatus.OK).body(new cn.com.selfsoft.smartcity.commons.http.ResultModel<>(new DataItem(info)));
    }

//    @Override
//    public ResponseEntity getRequirementsPage(HttpServletRequest request, Pageable page) {
//        Map<String, Object> queryParams = ParameterUtil.HumpToUnderline(request.getParameterMap(), "mark", "size", "page", "sort", "access_token");
//        Page<RequirementsEntity> pageData = this.requirementsService.page(queryParams, page);
//        for (RequirementsEntity pageDatum : pageData) {
//            Long id = pageDatum.getId();
//            List<Files> files = fileRelationService.findFilesByObjId(id);
//            if (files != null) {
//                pageDatum.setFiles(files);
//            }
//        }
//        return ResponseEntity.status(HttpStatus.OK).body(new cn.com.selfsoft.smartcity.commons.http.ResultModel<>(new DataPage(pageData)));
//    }

    @Override
    public ResponseEntity getRequirementsById(String id) {
        RequirementsEntity requirementsEntity = this.requirementsService.load(id);
        Long objId = requirementsEntity.getId();
        List<Files> files = fileRelationService.findFilesByObjId(objId);
        requirementsEntity.setFiles(files);
        return ResponseEntity.status(HttpStatus.OK).body(new cn.com.self.apis.core.vo.ResultModel<>(requirementsEntity));
    }

    @Override
    public RequirementsDTO2 getRequirementsById2(Map<String, Object> queryParams) {
        CustomPage<RequirementsDTO2> page = new CustomPage<>(10,1);
        RequirementsDTO2 requirementsDTO2 = requirementsMapper.queryRequirementsEntityList(page,queryParams).getRows().get(0);
        Long objId = requirementsDTO2.getId();
        //字典回显
        setData(requirementsDTO2);
        //附件
        List<Files> files = fileRelationService.findFilesByObjId(objId);
        requirementsDTO2.setFiles(files);
        return requirementsDTO2;
    }

    @Override
    public ICustomPage<RequirementsDTO2> queryRequirementsEntityList(Map<String, Object> queryParams, Pageable pageable) {
        CustomPage<RequirementsDTO2> page = new CustomPage<>(pageable.getPageNumber(),pageable.getPageSize());

        String compareSql=getCompareSql(queryParams.get("min_amount"),queryParams.get("max_amount"));
        if(compareSql !=null){
            queryParams.put("compare_sql",compareSql);
        }
        ICustomPage<RequirementsDTO2> result=requirementsMapper.queryRequirementsEntityList(page,queryParams);
        if(result !=null && result.getRows() !=null){
            setDataType(result.getRows());
        }
        return result;

    }

    /**
     * 价格区间匹对
     * @return
     */
    public String getCompareSql(Object min,Object max){
        if(StringUtils.isEmpty(min) && StringUtils.isEmpty(max)){
            return null;
        }else if(!StringUtils.isEmpty(min) && StringUtils.isEmpty(max)){
            return " t1.budget_amount >="+min+" ";
        }else if(StringUtils.isEmpty(min) && !StringUtils.isEmpty(max)){
            return " t1.budget_amount <="+max+" ";
        }else {
            return " t1.budget_amount >="+min+" and t1.budget_amount <="+max+" ";
        }

    }

    /**
     * 字典回显
     */
    public void setDataType(List<RequirementsDTO2> list) {
        if (list != null && list.size() > 0) {
            for (RequirementsDTO2 mv : list) {
                setData(mv);
            }
        }
    }

    public void setData(RequirementsDTO2 mv) {
        Object scope_val = redisUtils.get(RedisCodeUtil.datatype_name + RedisCodeUtil.scope + mv.getScope());
        Object requirementsState_val = redisUtils.get(RedisCodeUtil.datatype_name + RedisCodeUtil.projectStatus + mv.getRequirementsState());
        Object requirementsType_val = redisUtils.get(RedisCodeUtil.datatype_name + RedisCodeUtil.requirements_type + mv.getRequirementsType());
        mv.setScope_val(scope_val);
        mv.setRequirementsState_val(requirementsState_val);
        mv.setRequirementsType_val(requirementsType_val);
    }

    @Override
    public ResponseEntity getRequirementsCountByDate() {
        //获取单天天0点时间
        Date dateTodayZero = DateUtils.getDateTodayZero();
        String today = DateUtils.formatDate(dateTodayZero, "yyyy-MM-dd HH:mm:ss");
        //获取第二天0点时间
        Date dateTomorrowZero = DateUtils.getDateTomorrowZero();
        String tomorrow = DateUtils.formatDate(dateTomorrowZero, "yyyy-MM-dd HH:mm:ss");
        QueryWrapper<RequirementsEntity> requirementsEntityQueryWrapper = new QueryWrapper<>();
        requirementsEntityQueryWrapper.apply("create_date >= ' " + today + " '");
        requirementsEntityQueryWrapper.apply("create_date < ' " + tomorrow + " '");
        Integer integer = requirementsMapper.selectCount(requirementsEntityQueryWrapper);
        return ResponseEntity.status(HttpStatus.OK).body(new cn.com.selfsoft.smartcity.commons.http.ResultModel<>(integer));
    }


}
